<template>

  <!-- 搜索栏 -->
   <div class="title" style=""> 

     <p style="font-size: 1.2em;line-height: 100%; margin: 0;text-align: center;">防具表一览</p> <br>

      <el-form :inline="true" :model="searchName" class="form" style="margin: -14px 0px 0px 0px;" >
        <el-form-item label="防具名称">
          <el-input v-model="searchName.name" placeholder="请输入防具名称"/>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
        </el-form-item>

        <el-form-item style="float:right;margin: 0px 0px 0px 0px;">
          <el-button type="warning" plain @click="addArmor">添加防具</el-button>
        </el-form-item>

        <el-form-item style="float:right;margin: 0px 20px 0px 0px;">
          <el-button type="danger" plain @click="batchDel">批量删除</el-button>
        </el-form-item>
      </el-form>
   </div>


<!-- 表格 -->
  <el-table :data="armorList" style="width: 100% ;height: 86%;margin: -14px 0px 0px 0px;" 
    @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="30" />

      <el-table-column fixed prop="image" label="物品图片" width="100" >
             <template #default="scope">
              <img :src="scope.row.image" width="50">
            </template>
      </el-table-column>

      <el-table-column prop="armorName" label="防具名称" width="150" />
      <el-table-column prop="currentPrice" label="物品单价" sortable  width="130" />
      <el-table-column prop="armorEffect" label="防具效果" width="150" />
      <el-table-column prop="durability" label="耐久度" sortable  width="100" />
      <el-table-column prop="sellableDurability" label="可出售耐久" width="150" />
      
      <el-table-column  label="价格变化" width="100">
        <el-button type="success">变化表</el-button>
      </el-table-column>
       <el-table-column label="操作" width="150"> 
         <template #default="scope">
        <el-button type="primary" size="small" @click="update(scope.row.id)">编辑</el-button>
        <el-button type="danger" size="small" @click="delById(scope.row.id)">删除</el-button>
      </template>
       </el-table-column>
      

    </el-table>

    
         <!-- 分页组件Pagination -->
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[5, 10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style=" height: 33px; margin-top: 2px;"
    />



    <!-- 新增 / 修改的 DiaLog对话框 -->
 <el-dialog v-model="dialogFormVisible" :title="formTitle">
    <el-form :model="armorForm" :rules="rules" ref="armorFormRef">
      <!-- 第一行 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="护具名"   :label-width="labelWidth" prop="armorName">
            <el-input v-model="armorForm.armorName" placeholder="请输入护具名,长度2-20"/>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="当前单价"  :label-width="labelWidth" prop="currentPrice">
            <el-input v-model="armorForm.currentPrice"  placeholder="请输入当前价格" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 第二行 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="效果" :label-width="labelWidth" prop="armorEffect">
            <el-input v-model="armorForm.armorEffect"  placeholder="请输入防具效果,长度50以内" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="耐久" :label-width="labelWidth" prop="durability">
            <el-input v-model="armorForm.durability" placeholder="请输入防具耐久" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="可出售耐久" :label-width="labelWidth" prop="sellableDurability">
            <el-input v-model="armorForm.sellableDurability"  placeholder="请输入薪资"/>
          </el-form-item>
        </el-col>
      </el-row>
          <!--
            upload组件： 
              action: 请求 URL --- 文件上传接口的url
              on-success: 文件上传成功时的钩子
              before-upload: 上传文件之前的钩子，参数为上传的文件 【通常在该函数中进行文件校验】
          -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="头像"  :label-width="labelWidth">
            <el-upload
              class="avatar-uploader"
              action="/api/upload/fileUpload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
                :headers="uploadHeaders"
            >
              <img v-if="armorForm.image" :src="armorForm.image" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>


      <!-- 第七行 内部数组，本模块不用
      <el-row :gutter="5" v-for="expr in emp.exprList">
        <el-col :span="10">
          <el-form-item label="时间" size="small" :label-width="labelWidth">
            <el-date-picker type="daterange" v-model="expr.exprDate" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD"/>
          </el-form-item>
        </el-col>    
        <el-col :span="6">
          <el-form-item label="公司" size="small">
            <el-input placeholder="公司名称" v-model="expr.company"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="职位" size="small">
            <el-input placeholder="职位名称" v-model="expr.job"/>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-form-item size="small">
            <el-button type="danger" @click="delWorkItem(expr)">- 删除</el-button>
          </el-form-item>
        </el-col>
      </el-row>
-->


    </el-form>



    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="save(armorFormRef)">确定</el-button>
      </span>
    </template>
  </el-dialog>



</template>
<script setup lang="ts">
import { onMounted ,ref,computed} from "vue";
import type {PaginationParam,ArmorsModel,ArmorsModellArray} from "@/api/model/model"
 import { queryArmorsPageApi ,queryArmorByIdApi,updateApi,addApi,deleteApi,batchDeleteApi} from "@/api/armors";
import { ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadProps } from 'element-plus';
import { Plus } from '@element-plus/icons-vue'; // 按需导入图标


import { useLoginEmpStore } from '@/stores/loginEmp';
const loginEmpStore = useLoginEmpStore();
// 从 store 中获取 token 并计算请求头
const uploadHeaders = computed(() => {
  const loginEmp = loginEmpStore.getLoginEmp();
  return loginEmp && loginEmp.token
    ? { 'token': loginEmp.token }
    : {};
});

const dialogFormVisible = ref(false); // 初始隐藏对话框
const labelWidth = ref<number>(100)
const formTitle = ref<string>("");


 const armorForm = ref<ArmorsModel>({
  image: '',
  armorName: '',
  currentPrice: 0,
  armorEffect: '',
  durability: 0,
  sellableDurability: ''
})

//定义表单校验规则
const armorFormRef = ref<FormInstance>()
const rules = ref<FormRules<ArmorsModel>>({
  armorName: [
    { required: true, message: '防具名为必填项', trigger: 'blur' },
    { min: 2, max: 20, message: '防具名长度为2-20个字', trigger: 'blur' }
  ],
  currentPrice: [
    { required: false, message: '价格', trigger: 'blur' },
    {  min: 0, max: 10, message: '价格', trigger: 'blur' }
  ],
  armorEffect: [
    { required: false, message: '防具效果可以没有', trigger: 'blur' }
  ],
  durability: [
    { required: true, message: '耐久为必填项', trigger: 'blur' },
    {  min: 0, max: 10, message: '耐久度需在20到150之间', trigger: 'blur' }
  ],
  sellableDurability: [
    { required: false, message: '可售卖的耐久为必填项', trigger: 'blur' },
    {  min: 0, max: 10, message: '耐久度需在80到150之间', trigger: 'blur' }
  ]
})
//重置校验规则
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const addArmor = () => {
  console.log("addArmor");
  dialogFormVisible.value = true
  resetForm(armorFormRef.value) //重置校验规则
  formTitle.value = '新增防具'

  //初始化 表单数据
  armorForm.value = {
      image: '',
      armorName: '',
      currentPrice: 0,
      armorEffect: '',
      durability: 0,
      sellableDurability: ''
  }
  
}

// --------------------------------> 修改防具
//1. 查询回显
const update = async (id: number) => {
  dialogFormVisible.value = true
  formTitle.value = '修改防具'
  resetForm(armorFormRef.value) //重置校验规则

  //发送请求, 根据ID查询信息
  const result = await queryArmorByIdApi(id)
  if(result.code) {
    armorForm.value = result.data

    //做一步处理 - expr.exprDate
    // const exprList = emp.value.exprList
    // if(exprList && exprList.length>0){
    //   exprList.forEach(expr => {
    //     expr.exprDate = [expr.begin,expr.end]
    //   })
    // }
  }
}

//员工 ----> 新增  / 修改
const save = async (form:FormInstance | undefined) => {
  //校验表单, 如果校验通过, 再提交表单
  if (!form) return
  await form.validate(async (valid, fields) => { //valid 为true, 通过 ; false, 不通过
    if (valid) { //通过

      //发送异步请求保存数据
      let result ;
      if(armorForm.value.id){ //有id, 执行修改
        result = await updateApi(armorForm.value)
      }else { //没有id,执行新增
        result = await addApi(armorForm.value)
      }
      
      if(result.code){//保存成功, 提示成功信息, 关闭对话框, 重新查询
        ElMessage.success('操作成功')
        dialogFormVisible.value = false
        search()
      }else {//保存失败, 提示错误信息
        ElMessage.error(result.msg)
      }
    } else { //不通过
      ElMessage.error('表单校验失败, 不能提交')
    }
  })
}
// ----------------------------------- 删除的逻辑
const delById = (id:number) => {
  ElMessageBox.confirm('您确定要删除该数据吗?', '删除',
    {confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'}
  ).then(async () => { //点击确定按钮
    //发送请求, 删除数据
    const result = await deleteApi(id)
    if(result.code){
      ElMessage.success('删除成功')
      search()
    }else {
      ElMessage.error(result.msg)
    }
  })
}

const selectIds = ref<(number| undefined)[]>([]) //封装勾选的id
const handleSelectionChange = (val: ArmorsModel[]) => {
  selectIds.value = val.map(e => e.id) //map方法-遍历数组并对其中的元素进行进一步的处理, 并将结果封装到一个新的数组中
}


const batchDel = () => {
  ElMessageBox.confirm('您确定要删除该数据吗?', '删除防具',
    {confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'}
  ).then(async () => { //点击确定按钮
    //发送请求, 删除数据
    const result = await batchDeleteApi(selectIds.value) 
    if(result.code){
      ElMessage.success('删除成功')
      search()
    }else {
      ElMessage.error(result.msg)
    }
  })
}

const armorList = ref<ArmorsModellArray>([])
const pagination = ref<PaginationParam>({currentPage: 1, pageSize: 20, total: 0})


type SearchEmpModel = {
  name: string, 

}
//定义搜索栏表单封装对象
const searchName = ref<SearchEmpModel>({
  name: ''

})
const search = async () => {
  const result = await queryArmorsPageApi(
    pagination.value.currentPage,
    pagination.value.pageSize
  )
 console.log("bbbbbbbbb");
  if(result.code) {
    console.log(result);
    armorList.value= result.data.records
    console.log( "result"+result.data.records)
    console.log( "armorList"+armorList);
    
    pagination.value.total = result.data.total //总记录数
  }
}

//每页展示记录数变化时触发
const handleSizeChange = (val: number) => { //val: 记录数 50
  pagination.value.pageSize = val
  search()
}

//页码变化时出发
const handleCurrentChange = (val: number) => { //val: 页码
  pagination.value.currentPage = val
  search()
}


//文件上传
//文件上传成功后触发
const handleAvatarSuccess: UploadProps['onSuccess'] = (response,uploadFile) => {
  armorForm.value.image = response.data
}

//文件上传前触发
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('文件格式不正确')
    return false //不执行上传操作
  }
  return true
}

onMounted(()=>{
  
search()
})

</script>

<style scoped>
    body{
        background-color: #bfa;
    }



    .avatar-uploader .avatar {
      width: 78px;
      height: 78px;
      display: block;
    }
    .avatar-uploader .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 78px;
      height: 78px;
      text-align: center;
      border: 1px dashed;
    }
</style>